<route lang="yaml">
  meta:
    title: 仓库管理
  </route>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

const searchKeyword = ref('')
const city = ref<string[]>([]) // 多选需要数组类型
interface Warehouse {
  id: number
  name: string
  city: string
  address: string
  principal: string
  phone: string
  createTime: string
  status: '启用' | '禁用'
}

// 表格数据
const tableData = ref<Warehouse[]>([
  {
    id: 1,
    name: '中心仓库',
    city: '上海',
    address: '浦东新区张江路123号',
    principal: '张三',
    phone: '13800138000',
    createTime: '2023-01-01',
    status: '启用',
  },
  {
    id: 2,
    name: '分仓1号',
    city: '北京',
    address: '朝阳区望京路456号',
    principal: '李四',
    phone: '13900139000',
    createTime: '2023-02-01',
    status: '禁用',
  },
])

// 弹窗控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

// 表单数据
const addFormData = reactive<Omit<Warehouse, 'id'>>({
  name: '',
  city: '',
  address: '',
  principal: '',
  phone: '',
  createTime: new Date().toISOString().split('T')[0],
  status: '启用',
})

const editFormData = reactive<Warehouse>({
  id: 0,
  name: '',
  city: '',
  address: '',
  principal: '',
  phone: '',
  createTime: '',
  status: '启用',
})

// 城市选项
const cityOptions = [
  { value: '上海', label: '上海' },
  { value: '北京', label: '北京' },
  { value: '广州', label: '广州' },
  { value: '深圳', label: '深圳' },
]

// 验证规则
const rules = reactive({
  name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
  city: [{ required: true, message: '请选择城市', trigger: 'change' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  principal: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' },
  ],
})

// 新增仓库
function handleAdd() {
  addFormRef.value?.resetFields()
  addDialogVisible.value = true
}

// 编辑仓库
function handleEdit(row: Warehouse) {
  Object.assign(editFormData, row)
  editDialogVisible.value = true
}

// 删除仓库
async function handleDelete(row: Warehouse) {
  try {
    await ElMessageBox.confirm(
      `确定删除仓库【${row.name}】吗？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }
  catch {
    // 取消删除
  }
}

// 提交新增
function submitAdd() {
  addFormRef.value?.validate((valid) => {
    if (valid) {
      const newId = tableData.value.length
        ? Math.max(...tableData.value.map(w => w.id)) + 1
        : 1

      tableData.value.push({
        id: newId,
        ...addFormData,
      })
      addDialogVisible.value = false
      ElMessage.success('新增成功')
    }
  })
}

// 提交编辑
function submitEdit() {
  editFormRef.value?.validate((valid) => {
    if (valid) {
      const index = tableData.value.findIndex(item => item.id === editFormData.id)
      if (index > -1) {
        tableData.value.splice(index, 1, { ...editFormData })
        editDialogVisible.value = false
        ElMessage.success('修改成功')
      }
    }
  })
}
</script>

<template>
  <div>
    <FaPageMain>
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            <span class="ml-1">新增</span>
          </el-button>
        </div>

        <div class="search-wrapper">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入仓库名称"
            clearable
            style="width: 200px;"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>

          <el-select
            v-model="city"
            multiple
            placeholder="城市"
            style="width: 200px;"
          >
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table
          :data="tableData"
          style="width: 100%;"
          max-height="calc(100vh - 200px)"
        >
          <el-table-column type="selection" />
          <el-table-column prop="name" label="仓库名称" />
          <el-table-column prop="city" label="城市" />
          <el-table-column prop="address" label="地址" />
          <el-table-column prop="principal" label="负责人" />
          <el-table-column prop="createTime" label="创建时间" />
          <el-table-column prop="status" label="启用状态" />
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <div class="flex items-center">
                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button type="danger" link @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pagination-wrapper">
        <el-pagination
          :page-size="20"
          :pager-count="11"
          layout="prev, pager, next"
          :total="tableData.length"
        />
      </div>
    </FaPageMain>

    <!-- 新增弹窗 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增仓库"
      width="600px"
    >
      <el-form
        ref="addFormRef"
        :model="addFormData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="addFormData.name" />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="addFormData.city" placeholder="请选择">
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addFormData.address" />
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-input v-model="addFormData.principal" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="addFormData.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="addFormData.status">
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitAdd">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑仓库"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editFormData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="仓库名称" prop="name">
          <el-input v-model="editFormData.name" disabled />
        </el-form-item>
        <el-form-item label="城市" prop="city">
          <el-select v-model="editFormData.city">
            <el-option
              v-for="item in cityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editFormData.address" />
        </el-form-item>
        <el-form-item label="负责人" prop="principal">
          <el-input v-model="editFormData.principal" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editFormData.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editFormData.status">
            <el-option label="启用" value="启用" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitEdit">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.search-wrapper {
  display: flex;
  gap: 12px;
}

.table-wrapper {
  margin-top: 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}
</style>
